const db = require("../db")
const { log } = require("console")
const db_execute = async (sql, params) => {
    if (!params) {
        return db.execute(sql, params); // 没有参数直接执行
    } else {
        const new_params = params.map(item => {
            if (typeof item === 'number') {
                return item.toString();  // 如果是数字，转换成字符串
            }
            return item;
        });
        return db.execute(sql, new_params); // 执行查询并传递转换后的参数
    }
}
log('考勤机器人已启动');
let testDay = "2025-02-01"
class AttendanceRobot {
    // 每天 0 点生成考勤表的空表
    static async robot1() {
        log('开始生成当天的空考勤表');
        try {
            const today = new Date(testDay).toISOString().split('T')[0]; // 获取今天的日期，格式为 YYYY-MM-DD

            // 获取所有员工ID
            const employees = await db_execute('SELECT employee_id FROM employees');
            // 为每个员工生成当天的空考勤记录
            for (const employee of employees[0]) {
                const employee_id = employee.employee_id;

                // 检查是否已经存在当天的考勤记录
                const existingRecord = await db_execute(
                    'SELECT * FROM employee_attendance WHERE employee_id = ? AND attendance_date = ?',
                    [employee_id, today]
                );
                if (existingRecord[0].length === 0) {
                    // 插入空的考勤记录
                    await db_execute(
                        'INSERT INTO employee_attendance (employee_id, attendance_date, check_in_time, check_out_time, status, created_at, updated_at) VALUES (?, ?, NULL, NULL, "缺勤", NOW(), NOW())',
                        [employee_id, today]
                    );
                    log('成功生成当天的空考勤表');

                }
            }

        } catch (error) {
            log('生成考勤表失败:', error.message);
        }
    }

    // 每天 23 点更新未打卡员工的考勤状态
    static async robot2() {
        log('开始更新未打卡员工的考勤状态');
        try {
            const today = new Date(testDay).toISOString().split('T')[0]; // 获取今天的日期，格式为 YYYY-MM-DD

            // 查询所有 check_out_time 为空的考勤记录
            const records = await db_execute(
                'SELECT * FROM employee_attendance WHERE attendance_date = ? AND check_out_time IS NULL',
                [today]
            );
            if (records[0].length === 0) {
                log('今天无员工缺勤');
                return
            }
            // 更新这些记录的 status 为 "缺勤"
            for (const record of records[0]) {
                await db_execute(
                    'UPDATE employee_attendance SET status = "缺勤", updated_at = NOW() WHERE employee_id = ? AND attendance_date = ?',
                    [record.employee_id, today]
                );
                log('成功更新未打卡员工的考勤状态');
            }

        } catch (error) {
            log('更新考勤状态失败:', error.message);
        }
    }
}

module.exports = AttendanceRobot